/*    
 * 五星电器公司拥有完全的版权   
 * 使用者必须经过许可
 *----------------------------------------------------------------------*
 * Copyright  (c) 2016 FiveStar Co.,Ltd. All rights reserved
 * Author       : FiveStar Development
 * Description  : FsAuthenticationManager.java
 *----------------------------------------------------------------------*
 * Change-History: Change history
 * Developer  Date      Description
 * shidong  2017年5月25日 Short description containing Message, Note ID or CR ID
 *----------------------------------------------------------------------*  
 */
package com.twp.auth.security;

import com.twp.auth.component.Md5Component;
import com.twp.auth.constants.ResultCodeConstants;
import com.twp.auth.domain.authority.Role;
import com.twp.auth.domain.authority.user.ManageUser;
import com.twp.auth.myexecption.MyBadCredentialsException;
import com.twp.auth.service.manage.RoleService;
import com.twp.auth.service.user.ManageUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;


/**
 * 此类功能描述
 *
 * @author shidong
 * @since JDK 1.8
 */
@Component
public class MyAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    private boolean forcePrincipalAsString = false;

    @Autowired
    private ManageUserService managerService;

    @Autowired
    Md5Component md5Component;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Autowired
    private RoleService roleService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        LinkedHashMap<String, String> detail_param = (LinkedHashMap<String, String>) authentication.getDetails();
        String scope = detail_param.getOrDefault("scope","app");

        // Determine username
        String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
        username = username.toLowerCase();

        UserDetails user = null;

        ManageUser manageruser = managerService.findAllByUserName(username);
        if (manageruser == null) {
            throw new MyBadCredentialsException("此用户无权限登录", ResultCodeConstants.UNAUTHORIZED);
        }

        if (!md5Component.matches(authentication.getCredentials().toString(),manageruser.getPassword()))
            throw new MyBadCredentialsException("密码不正确",ResultCodeConstants.errorPwd);

            //记录设备id
        if (manageruser.getStatus() == 0) {
            throw new MyBadCredentialsException("用户状态为无效",ResultCodeConstants.invalidUser);
        }

        //取用户角色列表
        //List<Role> list = roleService.queryRolesByUid(manageruser.getId());
       // List<Role> list = roleService.queryRolesByUid(3);
        List<Role> list = manageruser.getRoleList();
        List<GrantedAuthority> authoritys = new ArrayList<GrantedAuthority>();
        for (Role role : list) {
            authoritys.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        user = new org.springframework.security.core.userdetails.User(username, "", authoritys);


        Object principalToReturn = user;

        if (forcePrincipalAsString) {
            principalToReturn = user.getUsername();
        }
        return createSuccessAuthentication(principalToReturn, authentication, user);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,
                                                  UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
        return null;
    }
}
